﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace CdcFileToCsv
{
    class Program
    {
        static void Main(string[] args)
        {
            
            string path = System.IO.Path.GetDirectoryName(
               System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            StringBuilder sb = new StringBuilder();
            Uri uri = new Uri(path);
            System.IO.FileInfo file = null;
            String fileName = null;
            string[] files = System.IO.Directory.GetFiles(uri.LocalPath,"*.pdf");
            Regex regex = new Regex("(?<subj>[a-zA-Z]+?)_([a-zA-Z0-9 ]+_)*(?<date>[0-9]{6}([0-9]{2})?).pdf");
            Match m = null;
            string date = null, subj = null;
            DateTime dt = DateTime.Now;
            IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);

            System.IO.FileStream fs = new System.IO.FileStream(uri.LocalPath + @"\temp_" + dt.ToString("yyyyMMddhhmmss") + ".csv", System.IO.FileMode.CreateNew);
            System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);
            try
            {
                sw.WriteLine("Path;File;Title;Subject;Fdate;Reported;From;To");

                foreach (string fileStr in files)
                {
                    file = new System.IO.FileInfo(fileStr);

                    fileName = file.Name;
                    if (regex.IsMatch(fileName))
                    {
                        m = regex.Match(fileName);
                        date = m.Result("${date}");
                        subj = m.Result("${subj}");
                        if (date.Length == 6)
                            date += "01";
                        dt = DateTime.ParseExact(date, "yyyyMMdd", culture);
                        sw.WriteLine(m.Result(uri.LocalPath
                            + ";"+fileName+";" + fileName.Substring(subj.Length+1, fileName.Length - subj.Length-1 - 4)
                            + ";"+subj+";" + dt.ToString("dd/MM/yyyy") + ";0"));

                        //Console.WriteLine(m.Result(uri.LocalPath
                        //    + ";;" + fileName.Substring(0, fileName.Length - 4)
                        //    + ";${subj};" + dt.ToString("dd/MM/yyyy") + ";0"));
                    }
                    else
                    {
                        Console.WriteLine(fileName);
                    }
                }
            }
            finally
            {
                sw.Close();
                fs.Close();
            }
            Console.ReadLine();
        }
    }
}
